package com.xs.ahoi.hcxs.utils;

import com.alibaba.fastjson.JSON;

import java.text.DecimalFormat;
import java.util.Collection;
import java.util.Map;

/**
 * @author Date：2009-3-14
 * @version 1.0
 */
public class ObjectUtils {
    private static final String EMPTY = "";

    public static boolean isNull(Object obj) {
        return obj == null;
    }

    public static boolean isNotNull(Object obj) {
        return !isNull(obj);
    }

    public static boolean isEmpty(Collection<?> coll) {
        return isNull(coll) || coll.isEmpty();
    }

    public static boolean isNotEmpty(Collection<?> coll) {
        return !isEmpty(coll);
    }

    public static String toString(Object obj) {
        if (isNull(obj)) {
            return EMPTY;
        }

        return obj.toString();
    }

    public static int toInteger(Object obj) {
        if (obj instanceof Float) {
            return ((Float) obj).intValue();
        }
        String s = toString(obj);
        if (StringUtils.isNotEmpty(s)) {
            int i = s.indexOf(".");
            if (i > -1) {
                s = s.substring(0, i);
            }
            return Integer.valueOf(s);
        }
        return 0;
    }

    public static long toLong(Object obj) {
        if (obj instanceof Float) {
            return ((Float) obj).longValue();
        }
        String s = toString(obj);
        if (StringUtils.isNotEmpty(s)) {
            int i = s.indexOf(".");
            if (i > -1) {
                s = s.substring(0, i);
            }
            return Long.parseLong(s);
        }
        return 0;
    }

    /**
     * 保留n位小数
     */
    public static String toFix(float num, int n) {
        String format = "######0";
        if (n > 0) {
            format += ".";
            for (int i = 0; i < n; i++) {
                format += "0";
            }
        }
        return new DecimalFormat(format).format(num);
    }

    public static Map<String, Object> obj2Map(Object o) {
        return JSON.parseObject(JSON.toJSONString(o), Map.class);
    }

    public static void main(String[] args) {
        int i = toInteger(24.0);
        System.out.println(i);
    }


}